package com.zhrj.exam.tool;

import com.zhrj.exam.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class StartupInitializer implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private  UserService userService;
    private boolean initialized = false;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 确保只执行一次
        if (!initialized) {
            initialized = true;
            
            // 异步执行初始化任务
            new Thread(() -> {
                try {
                    // 延迟5秒等待所有组件完全初始化
                    Thread.sleep(5000);
                    
                    log.info("开始执行启动初始化任务...");
                    userService.updateUserInfo();
                    userService.exportUsersToMinio();
                    log.info("启动初始化任务完成");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.error("启动初始化任务被中断", e);
                } catch (Exception e) {
                    log.error("启动初始化任务执行失败", e);
                }
            }).start();
        }
    }
}